package cn.jxufe.utils;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.jxufe.bean.Message;

public class FileSaver {

	public static Message save(String string, HttpServletRequest request, MultipartFile uploadFile){
		// 创建一个通用的多部份解析器
    	CommonsMultipartResolver commonsMultipartResolver = new 
    			CommonsMultipartResolver(request.getSession().getServletContext());
    	// 设置编码
    	commonsMultipartResolver.setDefaultEncoding("utf-8");
		Message message = new Message();
		
		
    	// 判断 request 是否有文件上传，即多部份请求
    	if(commonsMultipartResolver.isMultipart(request)) {
    		// 转换成多部份request
    		MultipartHttpServletRequest multipartRequest = 
    				commonsMultipartResolver.resolveMultipart(request);
    		// 获取绝对路径
    		String upload_file_path=request.getSession().getServletContext().getRealPath("images/headImages");
    		
    		// 上传后记录的文件
    		File imageFile = new File(upload_file_path + "/" + uploadFile.getOriginalFilename());
    		
    		// 上传
    		try {
    			uploadFile.transferTo(imageFile);
				message.setCode(0);
				message.setMsg("文件上传成功:" + uploadFile.getOriginalFilename());
			} catch (Exception e) {
				message.setCode(0);
				message.setMsg("文件上传失败:" + uploadFile.getOriginalFilename());
				e.printStackTrace();
			} 
    	}
		return message;
	}

}
